package com.dudu.access;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.dudu.bean.PoolAbilityInfoBean;
import com.dudu.service.ILogService;
import com.dudu.service.impl.LogService;
import com.dudu.utils.DateUtils;
import com.dudu.utils.Encrypt;
import com.dudu.utils.HttpRequest;
import com.dudu.utils.ProperyResource;

/**
 * IMS 智通多方通话Util
 * 
 */
public class ImsUtils {
	private static final Logger log = core.util.Logger.getLogger(ImsUtils.class.getName());
	private static ILogService logService = new LogService();

	public static void main(String[] agr) {
		PoolAbilityInfoBean poolAbilityInfo = new PoolAbilityInfoBean();
		poolAbilityInfo.setDisplay_number("8659527143061");
		poolAbilityInfo.setCharge_number("8659527143061");
		poolAbilityInfo.setCharge_key("28039283");
		ImsUtils.talksV2("17001090120", "18511588389,17001090132", poolAbilityInfo, "0", "test,test", "1");
	}

	/**
	 * 智能多方通话
	 * 
	 * @param presenterNbrss
	 *            多方通话的主持人号码
	 * @param CalledNbr
	 *            多方通话的被叫号码
	 * @param poolAbilityInfo
	 *            配置显号对象
	 * @param display_mode
	 *            被叫号码显示模式：0为显示配置号码、1为显示主叫号码
	 * @param tts_content
	 *            前导音文本内容
	 * @param isRecord
	 *            是否录音(1：是 其他：否) 如果不传表示不录音
	 * @return
	 */
	public static JSONObject talksV2(String presenterNbr, String CalledNbr, PoolAbilityInfoBean poolAbilityInfo,
			String display_mode, String tts_content, String isRecord) {
		log.info("-----------TalksV2 begin");
		JSONObject object = new JSONObject();
		long begin = 0;
		long end = 0;
		double during;
		String result_desc = "";
		String result_status = "";
		String displayNbr = "";
		String currentTime = DateUtils.getCurrentTime();

		// 请求参数
		StringBuffer urlBuffer = new StringBuffer();
		// StringBuffer urlBuffer = new
		// StringBuffer(ProperyResource.getServiceUrl());
		urlBuffer.append("<Request><Head><MethodName>TalksV3</MethodName>");
		urlBuffer.append("<Spid>").append(ProperyResource.getSpId()).append("</Spid>");
		urlBuffer.append("<Appid>").append(ProperyResource.getAppId()).append("</Appid>");
		urlBuffer.append("<Passwd>").append(Encrypt.sha1Encrypt(ProperyResource.getPassword())).append("</Passwd>");
		urlBuffer.append("</Head><Body>");

		if (poolAbilityInfo != null) {
			displayNbr = poolAbilityInfo.getDisplay_number();
			urlBuffer.append("<DisplayNbr>").append(poolAbilityInfo.getDisplay_number().trim()).append("</DisplayNbr>");
			urlBuffer.append("<ChargeNbr>").append(poolAbilityInfo.getCharge_number().trim()).append("</ChargeNbr>");
			urlBuffer.append("<Key>").append(poolAbilityInfo.getCharge_key().trim()).append("</Key>");
		} else {
			object.put("result", "0007");
			object.put("describe", "显号未配置！");
			object.put("code", "0020");
			return object;
		}

		urlBuffer.append("<PresenterNbr>").append(presenterNbr).append("</PresenterNbr>");
		urlBuffer.append("<CalledNbr>").append(CalledNbr).append("</CalledNbr>");
		urlBuffer.append("<DisplayNbrMode>").append(display_mode).append("</DisplayNbrMode>");
		urlBuffer.append("<PlayMarkedWords>1</PlayMarkedWords>");
		urlBuffer.append("<TTSContent>").append(tts_content).append("</TTSContent>");
		urlBuffer.append("<Record>").append(isRecord).append("</Record>");
		urlBuffer.append("</Body></Request>");
		String url = ProperyResource.getServiceUrl() + "?postData=" + URLEncoder.encode(urlBuffer.toString());
		log.info("-------TalksV2 url:" + url);
		// log.info("-------TalksV2 url:" + urlBuffer.toString().replaceAll("<",
		// "%3c").replaceAll(">", "%3e"));
		try {
			// urlBuffer.toString().replaceAll("<", "%3c").replaceAll(">",
			// "%3e")
			// String url= URLEncoder.encode(urlBuffer.toString());
			begin = Calendar.getInstance().getTimeInMillis();
			String data = HttpRequest.getDataThreeTime(url);
			// String data =
			// HttpRequest.getDataThreeTime(ProperyResource.getServiceUrl()+urlBuffer.toString().replaceAll("<",
			// "%3c").replaceAll(">", "%3e").replaceAll("/", "%2F"));
			end = Calendar.getInstance().getTimeInMillis();
			log.info("IMS TalksV2 response:" + data);
			// 判断如果返回值为null，则说明接口调用异常，返回异常通知
			if (StringUtils.isBlank(data)) {
				object.put("sessionId", "");
				// ‘0007’默认成为IMS通话发起异常
				object.put("result", "0007");
				object.put("describe", "Talks接口调用异常,可能网络连接失败！");
				object.put("code", "0020");
			} else {
				log.info("-----TalksV2 response:" + data);
				Document doc = DocumentHelper.parseText(data);
				Element root = doc.getRootElement();
				Element head = root.element("Head");
				object.put("sessionId", head.elementTextTrim("Sessionid"));
				object.put("result", head.elementTextTrim("Result"));
				object.put("describe", head.elementTextTrim("ResultDesc"));
				object.put("code", "0000");
				object.put("displayNbr", displayNbr);

				result_desc = data;
				result_status = head.elementTextTrim("Result");
			}
		} catch (Exception e) {
			log.info("------IMS发起电话会议出现异常！----");
			result_desc = "TalksV2 接口调用异常";
			result_status = "-1";
			object.put("sessionId", "");
			// ‘0007’默认成为IMS通话发起异常
			object.put("result", "0007");
			object.put("describe", "Talks接口调用异常");
			object.put("code", "0020");
		}
		try {
			during = Double.valueOf((end - begin)) / 1000;
			logService.logIms(during, "TalksV2", url, result_desc, result_status, currentTime, "IMS", presenterNbr);
		} catch (Exception e) {
			log.info("------IMS发起电话会议日志异常！----");
		}

		return object;
	}

	/**
	 * 智能多方通话过程中新增成员
	 * 
	 * @return
	 */
	public static JSONObject talksV2Add(String sessionid, String CalledNbr) {
		log.info("-----------TalksV2Add begin");
		JSONObject object = new JSONObject();
		long begin = 0;
		long end = 0;
		double during;
		String result_desc = "";
		String result_status = "";
		String currentTime = DateUtils.getCurrentTime();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
		String timestamp = sdf.format(Calendar.getInstance().getTime());
		// 请求参数
		StringBuffer urlBuffer = new StringBuffer();
		urlBuffer.append("<Request><Head><MethodName>TalksV3Add</MethodName>");
		urlBuffer.append("<Spid>").append(ProperyResource.getSpId()).append("</Spid>");
		urlBuffer.append("<Appid>").append(ProperyResource.getAppId()).append("</Appid>");
		urlBuffer.append("<Passwd>").append(Encrypt.sha1Encrypt(ProperyResource.getPassword())).append("</Passwd>");
		urlBuffer.append("<Timestamp>").append(timestamp).append("</Timestamp>");
		urlBuffer
				.append("<Authenticator>")
				.append(Encrypt.sha1Encrypt(timestamp + "IMS_QUERY" + ProperyResource.getSpId()
						+ ProperyResource.getPassword())).append("</Authenticator>");
		urlBuffer.append("</Head><Body>");
		urlBuffer.append("<Sessionid>").append(sessionid).append("</Sessionid>");
		urlBuffer.append("<CalledNbr>").append(CalledNbr).append("</CalledNbr>");
		urlBuffer.append("<PlayMarkedWords>1</PlayMarkedWords><TTSContent>欢迎进入电话会议</TTSContent>");
		urlBuffer.append("</Body></Request>");
		String url = ProperyResource.getServiceUrl() + "?postData=" + URLEncoder.encode(urlBuffer.toString());
		log.info("-------TalksV2Add url:" + url);
		try {
			begin = Calendar.getInstance().getTimeInMillis();
			String data = HttpRequest.getDataThreeTime(url);
			end = Calendar.getInstance().getTimeInMillis();
			log.info("-----TalksV2Add response:" + data);
			Document doc = DocumentHelper.parseText(data);
			Element root = doc.getRootElement();
			Element head = root.element("Head");
			object.put("result", head.elementTextTrim("Result"));
			object.put("errorMsg", head.elementTextTrim("ResultDesc"));
			object.put("code", "0000");

			result_desc = data;
			result_status = head.elementTextTrim("Result");
		} catch (Exception e) {
			log.info("------IMS智能多方通话过程中新增成员出现异常！----");
			result_desc = "TalksV2Add 接口调用异常";
			result_status = "-1";
		}

		try {
			during = Double.valueOf((end - begin)) / 1000;
			logService.logIms(during, "TalksV2Add", url, result_desc, result_status, currentTime, "IMS", "");
		} catch (Exception e) {
			log.info("------IMS智能多方通话过程中新增成员日志异常！----");
		}

		return object;
	}

	/**
	 * 智能多方通话过程中踢出成员
	 * 
	 * @return
	 */
	public static JSONObject talksV2Stop(String sessionid, String CalledNbr) {
		log.info("-----------TalksV2Stop begin");
		JSONObject object = new JSONObject();
		long begin = 0;
		long end = 0;
		double during;
		String result_desc = "";
		String result_status = "";
		String currentTime = DateUtils.getCurrentTime();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
		String timestamp = sdf.format(Calendar.getInstance().getTime());
		// 请求参数
		StringBuffer urlBuffer = new StringBuffer();
		urlBuffer.append("<Request><Head><MethodName>TalksV3Stop</MethodName>");
		urlBuffer.append("<Spid>").append(ProperyResource.getSpId()).append("</Spid>");
		urlBuffer.append("<Appid>").append(ProperyResource.getAppId()).append("</Appid>");
		urlBuffer.append("<Passwd>").append(Encrypt.sha1Encrypt(ProperyResource.getPassword())).append("</Passwd>");
		urlBuffer.append("<Timestamp>").append(timestamp).append("</Timestamp>");
		urlBuffer
				.append("<Authenticator>")
				.append(Encrypt.sha1Encrypt(timestamp + "IMS_QUERY" + ProperyResource.getSpId()
						+ ProperyResource.getPassword())).append("</Authenticator>");
		urlBuffer.append("</Head><Body>");
		urlBuffer.append("<Sessionid>").append(sessionid).append("</Sessionid>");
		urlBuffer.append("<CalledNbr>").append(CalledNbr).append("</CalledNbr>");
		urlBuffer.append("</Body></Request>");
		String url = ProperyResource.getServiceUrl() + "?postData=" + URLEncoder.encode(urlBuffer.toString());
		log.info("-------TalksV2Stop url:" + url);
		try {
			begin = Calendar.getInstance().getTimeInMillis();
			String data = HttpRequest.getDataThreeTime(url);
			end = Calendar.getInstance().getTimeInMillis();
			log.info("-----TalksV2Stop response:" + data);
			Document doc = DocumentHelper.parseText(data);
			Element root = doc.getRootElement();
			Element head = root.element("Head");
			object.put("result", head.elementTextTrim("Result"));
			object.put("errorMsg", head.elementTextTrim("ResultDesc"));
			object.put("describe", head.elementTextTrim("ResultDesc"));

			result_desc = data;
			result_status = head.elementTextTrim("Result");
		} catch (Exception e) {
			log.info("------IMS智能多方通话过程中踢出成员出现异常！----");
			result_desc = "TalksV2Stop 接口调用异常";
			result_status = "-1";
			object.put("result", "-1");
			object.put("code", "0306");
			object.put("errorMsg", "错误：" + e.getMessage());
			object.put("describe", "多方通话踢出参与人异常");
		}

		try {
			during = Double.valueOf((end - begin)) / 1000;
			logService.logIms(during, "TalksV2Stop", url, result_desc, result_status, currentTime, "IMS", "");
		} catch (Exception e) {
			log.info("------IMS智能多方通话过程中踢出成员日志异常！----");
		}

		return object;
	}

	/**
	 * 智能多方通话全部中断
	 * 
	 * @return
	 */
	public static JSONObject talksV2AllStop(String sessionid, boolean isMeet) {
		log.info("-----------TalksV2AllStop begin");
		JSONObject object = new JSONObject();
		long begin = 0;
		long end = 0;
		double during;
		String result_desc = "";
		String result_status = "";
		String currentTime = DateUtils.getCurrentTime();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
		String timestamp = sdf.format(Calendar.getInstance().getTime());
		// 请求参数
		StringBuffer urlBuffer = new StringBuffer();

		if (isMeet) {
			urlBuffer.append("<Request><Head><MethodName>TalksV3AllStop</MethodName>");
		} else {
			urlBuffer.append("<Request><Head><MethodName>DialStop</MethodName>");
		}

		urlBuffer.append("<Spid>").append(ProperyResource.getSpId()).append("</Spid>");
		urlBuffer.append("<Appid>").append(ProperyResource.getAppId()).append("</Appid>");
		urlBuffer.append("<Passwd>").append(Encrypt.sha1Encrypt(ProperyResource.getPassword())).append("</Passwd>");
		urlBuffer.append("<Timestamp>").append(timestamp).append("</Timestamp>");
		urlBuffer
				.append("<Authenticator>")
				.append(Encrypt.sha1Encrypt(timestamp + "IMS_QUERY" + ProperyResource.getSpId()
						+ ProperyResource.getPassword())).append("</Authenticator>");
		urlBuffer.append("</Head><Body>");
		urlBuffer.append("<Sessionid>").append(sessionid).append("</Sessionid>");
		urlBuffer.append("</Body></Request>");
		String url = ProperyResource.getServiceUrl() + "?postData=" + URLEncoder.encode(urlBuffer.toString());
		log.info("-------TalksV2AllStop url:" + url);
		try {
			begin = Calendar.getInstance().getTimeInMillis();
			String data = HttpRequest.getDataThreeTime(url);
			end = Calendar.getInstance().getTimeInMillis();
			log.info("-----TalksV2AllStop response:" + data);
			Document doc = DocumentHelper.parseText(data);
			Element root = doc.getRootElement();
			Element head = root.element("Head");
			object.put("result", head.elementTextTrim("Result"));
			object.put("errorMsg", head.elementTextTrim("ResultDesc"));
			object.put("code", "0000");

			result_desc = data;
			result_status = head.elementTextTrim("Result");
		} catch (Exception e) {
			log.info("------IMS结束多方通话出现异常！----");
			result_desc = "TalksV2AllStop 接口调用异常";
			result_status = "-1";
		}

		try {
			during = Double.valueOf((end - begin)) / 1000;
			if (isMeet) {
				logService.logIms(during, "TalksV2AllStop", url, result_desc, result_status, currentTime, "IMS", "");
			} else {
				logService.logIms(during, "DailStop", url, result_desc, result_status, currentTime, "IMS", "");
			}

		} catch (Exception e) {
			log.info("------IMS结束多方通话日志异常！----");
		}

		return object;
	}
}
